package com.zjut.szq.demo.action;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.zjut.szq.demo.action.commom.RandomCodeAction;
import com.zjut.szq.demo.model.Admin;
import com.zjut.szq.demo.service.AdminService;

@Controller
@ParentPackage("basePackage")
@Namespace("/")
public class AdminAction {

	private String userName;
	private String password;
	private String code;// 验证码

	@Autowired
	private AdminService adminService;

	/**
	 * 登录
	 * 
	 * @return
	 */
	@Action(value = "admin-login", 
		results = { @Result(name = "success", location = "/index.jsp", type = "redirect") })
	public String login() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		String radomcode = (String) session
				.getAttribute(RandomCodeAction.RANDOMCODEKEY);
		session.removeAttribute(RandomCodeAction.RANDOMCODEKEY);
		if (radomcode == null || radomcode.length() == 0) {
			ServletActionContext.getRequest().setAttribute("msg", "请输入验证码");
			return "tologin";
		} else if (!radomcode.equalsIgnoreCase(code)) {
			ServletActionContext.getRequest().setAttribute("msg", "验证码不正确");
			return "tologin";
		} else {
			Admin admin = adminService.login(userName, password);
			if (admin == null) {
				ServletActionContext.getRequest().setAttribute("msg", "用户密码不正确");
				return "tologin";
			} else {
				session.setAttribute("admin", admin);
				return "success";
			}
		}
	}
	
	/**
	 * 退出
	 * 
	 * @return
	 */
	@Action(value = "admin-logout")
	public String logout() {
		ServletActionContext.getRequest().getSession().invalidate();
		return "tologin";
	}

	public String getUserName() {
		return userName;
	}

	public String getPassword() {
		return password;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

}
